# -*- coding: utf-8 -*-
import requests
import bs4
from bs4 import BeautifulSoup

"""
爬取国内大学排名
"""


def getHtmlText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""


def fillUnivList(ulist, html):
    soup = BeautifulSoup(html, 'lxml')
    for tr in soup.find('tbody').children:
        if isinstance(tr, bs4.element.Tag):
            tds = tr('td')
            ulist.append([tds[0].string.strip(), tds[1].find('a').string.strip(),
                          str(tds[2]).split('>')[1].split('<')[0].strip(),
                          str(tds[3]).split('>')[1].split('<')[0].strip(), tds[4].string.strip(),
                          tds[5].string.strip()])


def printUnivList(ulist, num):
    # {1:{6}^10}：{6}表示使用format方法中的第几个参数，在这里表示在此处使用 format 的第7个参数 chr(12288)
    # chr(12288)：表示使用中文字符格式
    tplt = "{0:^6}\t{1:{6}^10}\t{2:{6}^6}\t{3:^6}\t{4:^6}\t{5:^6}"
    print(tplt.format("排名", "学校名称", "省市", "类型", "总分", "办学层次", chr(12288)))
    for i in range(num):
        u = ulist[i]
        print(tplt.format(u[0], u[1], u[2], u[3], u[4], u[5], chr(12288)))


if __name__ == '__main__':
    uinfo = []
    url = 'https://www.shanghairanking.cn/rankings/bcur/2021'
    html = getHtmlText(url)
    fillUnivList(uinfo, html)
    printUnivList(uinfo, 20)
